package com.pinyoumei.app.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Shader;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.support.v4.content.FileProvider;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.pinyoumei.app.R;
import com.pinyoumei.app.adapter.TeamPagerAdapter;
import com.pinyoumei.app.bean.VersionBean;
import com.pinyoumei.app.dialog.NoticeAnnouncementDialog;
import com.pinyoumei.app.fragment.FirstFragment;
import com.pinyoumei.app.fragment.FirstFragmentNew;
import com.pinyoumei.app.fragment.FourFragment;
import com.pinyoumei.app.fragment.SecondFragment;
import com.pinyoumei.app.fragment.ShoppingCartFragment;
import com.pinyoumei.app.fragment.ThirdFragment;
import com.pinyoumei.app.network.Constants;
import com.pinyoumei.app.utils.FileMD5;
import com.pinyoumei.app.utils.SPUtils;
import com.pinyoumei.app.utils.SignatureUtils;
import com.pinyoumei.app.utils.StatusBarUtils;
import com.pinyoumei.app.utils.ToastUtils;
import com.pinyoumei.app.utils.Utils;
import com.pinyoumei.app.view.dialog.APPUpdateDialog;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import io.reactivex.functions.Consumer;

/**
 * 主界面(底部点击按钮带有动画的)
 */
public class MainUIActivity extends BaseActivity implements View.OnClickListener {

    private APPUpdateDialog appUpdateDialog;
    //apk的文件地址
    private String mSavePath;
    //apk的名称
    private String apk_name;
    //apk的文件MainUIActivity
    private File apkFile;
    //版本更新的下载地址apk在服务器上的地址
    private String url_path = "";
    //服务器返回的apk的MD5值
    private String apkMD5;

    //    private SweetWarmDialog sweetWarmDialog;
    //时间戳
    private String show_time_stamp;
    private boolean close = false;
    //JPush
    public static boolean isForeground = false;
    public static final String MESSAGE_RECEIVED_ACTION = "com.example.jpushdemo.MESSAGE_RECEIVED_ACTION";
    public static final String KEY_TITLE = "title";
    public static final String KEY_MESSAGE = "message";
    public static final String KEY_EXTRAS = "extras";


    private boolean up_apk = false;

    private String[] tabText = {"首页", "开心团", "邀请好友", "我的"};

    private ArrayList<Fragment> fragments = new ArrayList<>();
    private ViewPager viewPager;
    private ImageView iv_visible;
    private LinearLayout ll_visible;
    private ImageView iv_2;
    private ImageView iv_3;
    private ImageView iv_4;
//    private ImageView iv_5;
    private TextView tv_2;
    private TextView tv_3;
    private TextView tv_4;
//    private TextView tv_5;

    public static MainUIActivity getInstance = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mainui);
        StatusBarUtils.setTranslucentStatus(this);

        InitView();



        //设置用户是第一次使用
        SPUtils.setIsFirstUse(MainUIActivity.this, false);


        //版本更新请求
        appVersion();
        if(getInstance ==null){
            getInstance = this;
        }

        new NoticeAnnouncementDialog(MainUIActivity.this).show();
    }



    private void InitView() {
        LinearLayout select_1 = findViewById(R.id.select_1);
        select_1.setOnClickListener(this);
        LinearLayout select_2 = findViewById(R.id.select_2);
        select_2.setOnClickListener(this);
        LinearLayout select_3 = findViewById(R.id.select_3);
        select_3.setOnClickListener(this);
        LinearLayout select_4 = findViewById(R.id.select_4);
        select_4.setOnClickListener(this);
//        LinearLayout select_5 = findViewById(R.id.select_5);
//        select_5.setOnClickListener(this);
        viewPager = findViewById(R.id.ViewPager);
        initViewPagerFragment(viewPager);

        iv_visible = findViewById(R.id.iv_visible);
        ll_visible = findViewById(R.id.ll_visible);
        iv_2 = findViewById(R.id.iv_2);
        iv_3 = findViewById(R.id.iv_3);
        iv_4 = findViewById(R.id.iv_4);
//        iv_5 = findViewById(R.id.iv_5);

        tv_2 = findViewById(R.id.tv_2);
        tv_3 = findViewById(R.id.tv_3);
        tv_4 = findViewById(R.id.tv_4);
//        tv_5 = findViewById(R.id.tv_5);
    }


    @Override
    protected void onResume() {
        super.onResume();
        requestPermission();//请求权限

    }


    //物理返回键的监听
    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                //销毁所有的Activity
                appManager.AppExit(MainUIActivity.this);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 请求权限
     */
    @SuppressLint("CheckResult")
    private void requestPermission() {
        RxPermissions rxPermission = new RxPermissions(this);
        rxPermission.requestEach(
                //读取SD卡权限
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                //定位权限
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                // 摄像头权限
                Manifest.permission.CAMERA,
                //打电话权限
                Manifest.permission.CALL_PHONE)
                .subscribe(new Consumer<Permission>() {
                    @SuppressLint("CheckResult")
                    @Override
                    public void accept(Permission permission) throws Exception {
                        if (permission.granted) {
                            // 用户已经同意该权限

                        } else {

                        }
                    }
                });
    }


    private void appVersion() {

        Map<String,Object> map = new HashMap<>();
        map.put("user_id", SPUtils.getAppUserId(MainUIActivity.this));
        map.put("type", 1);
        map.put("version_num", Utils.getVersionCode(MainUIActivity.this));


        OkGo.<String>post( Constants.APPVERSION_CHECK)
                .params("user_id", SPUtils.getAppUserId(MainUIActivity.this))
                .params("type", 1)
                .params("version_num", Utils.getVersionCode(MainUIActivity.this))
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {



                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }


                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);
                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();
                        VersionBean agencyRuleBean = gson.fromJson(response.body(), VersionBean.class);
                        if (agencyRuleBean.getCode() > 0 ){

                            url_path = agencyRuleBean.getResult().getApp_info().getApp_download_address();
                            apkMD5 = agencyRuleBean.getResult().getApp_info().getRemark();
                            //版本更新Dialog下载APK
                            appUpdateDialog = new APPUpdateDialog(MainUIActivity.this, agencyRuleBean.getResult().getApp_info().getDescription());

                            appUpdateDialog.setOnClickListener(new APPUpdateDialog.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    switch (view.getId()) {
                                        case R.id.relative_app_update://点击是版本更新按钮
                                            if (agencyRuleBean.getResult().getApp_info().getApp_download_address().equals("")) {
                                                Toast.makeText(MainUIActivity.this, "下载链接获取失败!", Toast.LENGTH_SHORT).show();
                                                return;
                                            }
                                            RxPermissions rxPermission = new RxPermissions(MainUIActivity.this);
                                            rxPermission.requestEach(
                                                    //写入SD卡权限
                                                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                                            ).subscribe(new Consumer<Permission>() {
                                                @Override
                                                public void accept(Permission permission) throws Exception {
                                                    if (permission.granted) {
                                                        // 用户已经写入SD卡权限
                                                        if (Manifest.permission.WRITE_EXTERNAL_STORAGE.equals(permission.name)) {

                                                            boolean haveInstallPermission;
                                                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                                                                //先获取是否有安装未知来源应用的权限
                                                                haveInstallPermission = getPackageManager().canRequestPackageInstalls();
                                                                if (!haveInstallPermission) {
                                                                    //8.0没有权限
                                                                    AlertDialog.Builder builder = new AlertDialog.Builder(MainUIActivity.this);
                                                                    builder.setTitle("安装应用需要打开未知来源权限，请去设置中开启权限");
                                                                    builder.setPositiveButton("开启", new DialogInterface.OnClickListener() {
                                                                        @Override
                                                                        public void onClick(DialogInterface dialog, int which) {
                                                                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                                                                                startInstallPermissionSettingActivity();
                                                                            }
                                                                        }
                                                                    });

                                                                    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                                                        @Override
                                                                        public void onClick(DialogInterface dialog, int which) {
                                                                            Toast.makeText(MainUIActivity.this, "取消将无法正常安装！", Toast.LENGTH_SHORT).show();
                                                                        }
                                                                    });
                                                                    builder.create().show();
                                                                    return;
                                                                } else {
                                                                    //8.0有未知来源权限
                                                                    installApk();
                                                                }
                                                            } else {
                                                                // 下载APK
                                                                installApk();
                                                            }


                                                        }
                                                    } else {//如果用户没有同意那么需要弹出提示框让用户去解决
                                                        Toast.makeText(MainUIActivity.this, "请打开读写手机存储权限!", Toast.LENGTH_SHORT).show();
                                                    }
                                                }
                                            });
                                            break;
                                        default:
                                    }
                                }
                            });


                            switch (agencyRuleBean.getResult().getIs_show_update()) {

                                case 1:
                                    //最新版本 强制更新
                                    appUpdateDialog.setCancelable(false);
                                    appUpdateDialog.setCanceledOnTouchOutside(false);
                                    appUpdateDialog.show();

                                    break;


                                default:
                                    break;
                            }










                        }else{
                            ToastUtils.showShort(agencyRuleBean.getMsg());
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }
                });
    }

    private String getTimeString() {
        //获取时间日期
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        String right_time = year + "-" + month + "-" + day;
        return right_time;
    }


    private void installApk() {
        //这个地方涉及到访问内存的权限问题 需要动态申请内存权限
        mSavePath = Environment.getExternalStorageDirectory().getPath() + "/sdcard/newpurseAPK/";
        File file = new File(mSavePath);
        // 判断文件目录是否存在
        if (!file.exists()) {
            file.mkdir();
        }
        apk_name = getFileName(url_path);//返回一个后缀名称为XX.apk字符串
        apkFile = new File(mSavePath, apk_name);
        File mFile = new File(mSavePath + apk_name);
        // 判断文件目录是否存在
        if (mFile.exists()) {//
            mFile.delete();
        }
        //显示进度条
        appUpdateDialog.showProgress();
        //下载

        OkGo.<File>get(url_path)//
                .tag(this)//
                .execute(new FileCallback(mSavePath, apk_name) {

                    @Override
                    public void onStart(Request<File, ? extends Request> request) {

                    }

                    @Override
                    public void onSuccess(Response<File> response) {
                        if (file.exists()) {//如果文件下载成功 先进行MD5校验
                            //下载的文件算出MD5值与服务器返回的MD5值进行比较 一致说明成功 不一致说明失败
                            if (FileMD5.verifyInstallPackage(mSavePath + apk_name, apkMD5)) {
                                Toast.makeText(MainUIActivity.this, "下载成功", Toast.LENGTH_SHORT).show();
                                appUpdateDialog.dismiss();
                                Intent intent = new Intent(Intent.ACTION_VIEW);
                                //版本在7.0以上是不能直接通过uri访问的
                                if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
                                    File file_path = (new File(mSavePath + apk_name));
                                    // 由于没有在Activity环境下启动Activity,设置下面的标签
                                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    //参数1:上下文, 参数2:Provider主机地址 和配置文件中保持一致,参数3:共享的文件
                                    Uri apkUri = FileProvider.getUriForFile(MainUIActivity.this, "com.pinyoumei.app.fileprovider", file_path);
                                    //添加这一句表示对目标应用临时授权该Uri所代表的文件
                                    intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
                                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                                } else {
                                    intent.setDataAndType(Uri.fromFile(new File(mSavePath + apk_name)), "application/vnd.android.package-archive");
                                }
                                MainUIActivity.this.startActivity(intent);

                            } else {
                                Toast.makeText(MainUIActivity.this, "MD5校验失败", Toast.LENGTH_SHORT).show();
                                appUpdateDialog.dismiss();
                                //file.delete();
                            }
                        }
                    }

                    @Override
                    public void onError(Response<File> response) {
                        Toast.makeText(MainUIActivity.this, "安装包下载失败", Toast.LENGTH_SHORT).show();
                        appUpdateDialog.dismiss();
                        File mFile = new File(mSavePath + apk_name);
                        // 判断文件目录是否存在
                        if (mFile.exists()) {
                            mFile.delete();
                        }
                    }

                    @Override
                    public void downloadProgress(Progress progress) {

                        appUpdateDialog.setProgress((int) (progress.fraction * 100));

                    }
                });


    }

    //从一个url中获取文件的名称
    protected String getFileName(String url) {
        return url.substring(url.lastIndexOf("/") + 1);
    }


    @RequiresApi(api = Build.VERSION_CODES.O)
    private void startInstallPermissionSettingActivity() {
        Uri packageURI = Uri.parse("package:" + getPackageName());
        //注意这个是8.0新API
        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
        startActivityForResult(intent, 10086);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10086 && resultCode == RESULT_OK) {
            installApk();
        }
    }

    //获取当前版本号
    private String getAppVersionName(Context context) {
        String versionName = "";
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo("com.pinyoumei.app", 0);
            versionName = packageInfo.versionName;
            if (TextUtils.isEmpty(versionName)) {
                return "";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return versionName;
    }

    private void initViewPagerFragment(ViewPager ViewPager) {
        TeamPagerAdapter mPagerAdapter = new TeamPagerAdapter(getSupportFragmentManager());
        fragments = new ArrayList<>();

        fragments.add(FirstFragmentNew.getInstance("首页"));
        fragments.add(SecondFragment.getInstance("开心团"));
        fragments.add(ThirdFragment.getInstance("邀请好友"));
        fragments.add(FourFragment.getInstance("我的"));
//        fragments.add(ShoppingCartFragment.getInstance("购物车"));


        mPagerAdapter.setTitles(tabText);
        mPagerAdapter.setFragments(fragments);
        ViewPager.setAdapter(mPagerAdapter);
        ViewPager.setOffscreenPageLimit(4);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.select_1:

                Select_Position(0);
                break;

            case R.id.select_2:
                Select_Position(1);
                break;

            case R.id.select_3:
                Select_Position(2);
                break;

            case R.id.select_4:
                Select_Position(3);
                break;

//            case R.id.select_5:
//                Select_Position(4);
//                break;
            default:
                break;
        }
    }

    public void Select_Position(int position) {
        iv_visible.setVisibility(View.GONE);
        ll_visible.setVisibility(View.VISIBLE);
        iv_2.setImageResource(R.mipmap.ic_main_hide_2);
        iv_3.setImageResource(R.mipmap.ic_main_hide_3);
        iv_4.setImageResource(R.mipmap.ic_main_hide_4);
//        iv_5.setImageResource(R.mipmap.ic_main_hide_5);
        setInitTextViewStyles(tv_2);
        setInitTextViewStyles(tv_3);
        setInitTextViewStyles(tv_4);
//        setInitTextViewStyles(tv_5);


        switch (position) {
            case 0:
                iv_visible.setVisibility(View.VISIBLE);
                ll_visible.setVisibility(View.GONE);
                viewPager.setCurrentItem(position);
                break;

            case 1:
                iv_2.setImageResource(R.mipmap.ic_main_show_2);
                setTextViewStyles(tv_2);
                viewPager.setCurrentItem(position);
                break;

            case 2:
                iv_3.setImageResource(R.mipmap.ic_main_show_3);
                setTextViewStyles(tv_3);
                viewPager.setCurrentItem(position);
                break;

            case 3:
                iv_4.setImageResource(R.mipmap.ic_main_show_4);
                setTextViewStyles(tv_4);
                viewPager.setCurrentItem(position);
                break;

            case 4:
//                iv_5.setImageResource(R.mipmap.ic_main_show_5);
//                setTextViewStyles(tv_5);
//                viewPager.setCurrentItem(position);
                break;
            default:
                break;
        }
    }


    /**
     * 设置textview 的颜色渐变
     *
     * @param text
     */

    public void setTextViewStyles(TextView text) {

        LinearGradient mLinearGradient = new LinearGradient(0, 0, 0, text.getPaint().getTextSize(), Color.parseColor("#26CB79"), Color.parseColor("#018D47"), Shader.TileMode.CLAMP);

        text.getPaint().setShader(mLinearGradient);

        text.invalidate();

    }

    /**
     * 设置textview 的颜色渐变
     *
     * @param text
     */

    public void setInitTextViewStyles(TextView text) {

        LinearGradient mLinearGradient = new LinearGradient(0, 0, 0, text.getPaint().getTextSize(), Color.parseColor("#666666"), Color.parseColor("#666666"), Shader.TileMode.CLAMP);

        text.getPaint().setShader(mLinearGradient);

        text.invalidate();

    }

}

